package com.irdstudio.apicenter.gateway.web.controller;


import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.core.weixin.WeiXinUtil;
import com.irdstudio.apicenter.gateway.web.MaccsControllerBus;
import com.irdstudio.apicenter.gateway.web.MaccsEntryServlet;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;

/**
 * 企业应用首次调用方法，返回用户ssoToken（页面与服务端凭证）
 * 
 * @author fmf
 * 
 */
@Controller
public class WenXinController implements IController {
	private final static Logger logger = LoggerFactory
			.getLogger(WenXinController.class);

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket,
			HttpServletRequest request, HttpServletResponse response)
			throws MaccsException {

		// 校验页面的ssoToken，返回ssoToken用户信息
		// 获取微信返回的code，用于获取userId;
		String code = inPacket.getValue("code");
		String appId = inPacket.getValue("state");
		MaccsPacket outPacket = new MaccsPacket();
		String model =WeiXinUtil.getWXProp("model");
		logger.info("model =" + model);
		
		// 获取微信令牌
		try {
			String mobile = "";
			if("prod".equals(model)){
				// 获取userId
				JSONObject userIdJson = null;
				userIdJson = WeiXinUtil.getUserId(code, appId);
				//获取零时票据，用于生成签名
				//String ticket = WeiXinUtil.getJsApiTicket(appId);
				if (!"0".equals(userIdJson.get("errcode").toString())) {
					String errmsg = userIdJson.getString("errmsg");
					// 重定向到错误页面
					throw new Exception(errmsg);
				}
				String userId = userIdJson.getString("UserId");
				// 获取用户信息
				JSONObject userInfoJson = null;
				userInfoJson = WeiXinUtil.getUserInfo(userId, appId);
				
				if (!"0".equals(userInfoJson.get("errcode").toString())) {
					String errmsg = userInfoJson.getString("errmsg");
					// 重定向到错误页面
					throw new Exception(errmsg);
				}
				
				//获取用户手机号码
				mobile = (String) userInfoJson.get("mobile");
			}else{
				mobile = inPacket.getValue("mobile");
			}
			//模拟登录业务系统，返回一些用户身份信息,
			MaccsEntryServlet maccsEntryServlet = new MaccsEntryServlet();
			MaccsControllerBus ctrlBus = maccsEntryServlet.getMaccsControllerBus("wxqyh");
			// 获取自定义私有交易
			MaccsTradeDefineVo newTradeDefine = ctrlBus.getMaccsTradeDefineVo("wxInitUserInfo.do");

			// 3.根据传入的实际登录交易ID去读取交易信息并交给转发交易控制器执行
			TradeForward tradeForward = new TradeForward();
			inPacket.addVariable("phone_num", mobile);
			inPacket.addVariable("currentuserid", mobile);
			inPacket.addVariable("createSession", true);
			View view = tradeForward.execute(newTradeDefine, inPacket, request, response);
			Map<String, Object> viewData = view.getMapData();
			
			String returnCode = (String) viewData.get("returnCode");
			if("999".equals(returnCode)){
				throw new Exception((String) viewData.get("returnMsg"));
			}
			Map<String, Object> returnData = (Map<String, Object>) viewData.get("returnData");
			
			//返回app服务器session
			String param = "?EMP_SID="+returnData.get("EMP_SID");
			System.out.println("重定向URL:"+WeiXinUtil.getWXProp("wx_url")+param);
			String url=WeiXinUtil.getWXProp("wx_url")+param;
			response.sendRedirect(url);
			outPacket = MaccsPacketUtil.makeSimpleSuccessPacket("OK!");
		} catch (Exception e1) {
			e1.printStackTrace();
			outPacket.addVariable("returnCode", "999");
			outPacket.addVariable("returnMsg",e1.getMessage());
		}finally{
			
		}

		return new JsonView(request, response, outPacket);
	}

}
